<?php

namespace App\V3\V3_2_7\Services;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\LogOutStorageModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ScanCodeAllocateStorageService
{
    /**
     *扫码调拨-基地
     * Author: zlf
     * Created at 2024/6/28 16:03
     * @param $data
     * @return array|null
     */
    public static function codeAllocateStorage($data): ?array
    {
        DB::beginTransaction();
        try {
            $result = [];
            $data['type'] = 11;
            $data['all_id_type'] = 8;
            $data['code_allocate_no'] = CommonService::getOrderNo(new LogOutStorageModel(), 'code_allocate_no', 'AC');//关联编号
            //仓库扫码调拨出库
            if (!empty($data['storage_id'])) {
                $result = ScanCodeOutStorageService::storageCodeOutStorage($data, 1);
            }
            //货架扫码调拨出库
            if (!empty($data['shelf_id'])) {
                $result = ScanCodeOutStorageService::shelfCodeOutStorage($data, 1);
            }
            //库位扫码调拨出库
            if (!empty($data['location_id'])) {
                $result = ScanCodeOutStorageService::locationCodeOutStorage($data, 1);
            }
            if (!empty($result['code'])) {
                throw new \RuntimeException($result['msg']);
            }
            $data['type'] = 9;
            $data['all_id_type'] = 10;
            //仓库扫码调拨入库
            if (!empty($data['in_storage_id']) && empty($data['in_shelf_id']) && empty($data['in_location_id'])) {
                $data['storage_id'] = $data['in_storage_id'];
                $result = ScanCodeInStorageService::storageCodeInStorage($data, 1);
            }
            //货架扫码调拨出库
            if (!empty($data['in_storage_id']) && !empty($data['in_shelf_id']) && empty($data['in_location_id'])) {
                $data['shelf_id'] = $data['in_shelf_id'];
                $result = ScanCodeInStorageService::shelfCodeInStorage($data, 1);
            }
            //库位扫码调拨出库
            if (!empty($data['in_storage_id']) && !empty($data['in_shelf_id']) && !empty($data['in_location_id'])) {
                $data['location_id'] = $data['in_location_id'];
                $result = ScanCodeInStorageService::locationCodeInStorage($data, 1);
            }
            if (!empty($result['code'])) {
                throw new \RuntimeException($result['msg']);
            }
            CommonService::operateResult($data['user_id'], $data['time'], $result, '扫码调拨成功！');
            DB::commit();
            return $result;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('扫码调拨（孵化）异常：' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }
}
